package com.luoran.bartalks.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.core.UserContext;
import com.luoran.bartalks.core.ext.Pageable;
import com.luoran.bartalks.entity.BaseInfo;
import com.luoran.bartalks.service.IBtMaterielMoveService;
import com.luoran.bartalks.service.IBtPlanBizPicService;
import com.luoran.bartalks.utils.CellPoint;
import com.luoran.bartalks.utils.ChangeImageSizeUtil;
import com.luoran.bartalks.utils.ExcelWriteImgUtil;

/**
 * 货物移动追溯信息报表
 * 
 * @author wmm 2018年5月04日 上午10:13:30
 */
@Controller
@RequestMapping("/report/material")
public class BtMaterialMoveAction implements Pageable {
	private static final Logger log = LoggerFactory.getLogger(BtMaterialMoveAction.class);
	
	@Autowired
	private IBtMaterielMoveService service;
	@Autowired
	private IBtPlanBizPicService picService;

	
	@Override
	public PageQuery<? extends BaseInfo> getQueryList(PageQuery<? extends BaseInfo> pageQuery) {
		log.info("获取货物相关信息列表数据,page:" + pageQuery.getPageNumber() + "size:" + pageQuery.getPageSize());
		@SuppressWarnings("unchecked")
		Map<String, String> map = (Map<String, String>) pageQuery.getParas();
		map.put("companyId", UserContext.get().getCompanyId());// 添加查询参数（公司ID）
		if (StringUtils.isEmpty(pageQuery.getOrderBy())) {
			pageQuery.setOrderBy("operation_date DESC");
		}
		pageQuery.setPageSize(50);// 设置分页记录条数
		return service.getQueryList(pageQuery);
	}
	
	
	@RequestMapping
	public String success() {
		log.info("跳转货物相关信息报表页面");
		return "/reportForm/materialMove";
	}
	
	/**
	 * 查看装卸货记录相对应的图片数量
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/photos/number/{id}")
	@ResponseBody
	public JSONObject getPhotosNumber(@PathVariable String id) {
		JSONObject result = new JSONObject();
		int num = picService.getPicNum(id);
		if (num != 0) {
			if (num == 1) {
				if ("/bartalks/not-photo.png".equals(picService.getPics(id).get(0))) {
					result.put("state", false);
					result.put("number", 0);
				} else {
					result.put("state", true);
					result.put("number", 1);
				}
			} else {
				result.put("state", true);
				result.put("number", num);
			}
		} else {
			result.put("state", false);
			result.put("number", 0);
		}
		return result;
	}

	/**
	 * 查看打尺记录相对应的图片
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/photos/{id}")
	@ResponseBody
	public JSONObject getPhotos(@PathVariable String id) {
		JSONObject result = new JSONObject();
		List<String> pics = picService.getPics(id);
		if (pics != null && pics.size() != 0) {
			result.put("state", true);
			result.put("piclist", pics);
		} else {
			result.put("state", false);
			result.put("msg", "访问图片出错!");
		}
		return result;
	}

	@GetMapping("/export")
	public void export(HttpServletRequest req, HttpServletResponse res) throws IOException {
		String jsonstr = req.getParameter("json");
		JSONObject json = JSONObject.parseObject(jsonstr);
		String fileName = "货物追溯报表" + new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			createWorkBook(json).write(os);
		} catch (IOException e) {
			e.printStackTrace();
			log.info("生成Excel错误");
			return;
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		// 设置response参数
		res.reset();
		res.setContentType("application/vnd.ms-excel;charset=utf-8");
		res.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		ServletOutputStream out = res.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
	}

	// 创建excel
	public HSSFWorkbook createWorkBook(JSONObject json) throws IOException {
		log.info("创建excel");
		// 创建excel工作簿
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 创建工作表sheet
		HSSFSheet sheet = workbook.createSheet("列表");
		// 单元格格式(用于标题)
		HSSFCellStyle csm = workbook.createCellStyle();
		HSSFFont ft = workbook.createFont();
		ft.setFontName("宋体");
		ft.setFontHeightInPoints((short) 16);
		ft.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗
		csm.setFont(ft);
		csm.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
		csm.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
		csm.setLocked(true);
		csm.setWrapText(true);// 自动换行
		// 背景色
		csm.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		csm.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

		// 单元格格式(用于列名)
		HSSFCellStyle csdt = workbook.createCellStyle();
		HSSFFont fdt = workbook.createFont();
		fdt.setFontName("微软雅黑");
		fdt.setFontHeightInPoints((short) 10);
		ft.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗
		csdt.setFont(fdt);
		csdt.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
		csdt.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
		csdt.setLocked(true);
		csdt.setWrapText(true);// 自动换行

		// 单元格格式(用于列表)
		HSSFCellStyle csdd = workbook.createCellStyle();
		HSSFFont fdd = workbook.createFont();
		fdd.setFontName("微软雅黑");
		fdd.setFontHeightInPoints((short) 8);
		fdd.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
		csdd.setFont(fdd);
		csdd.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
		csdd.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
		csdd.setLocked(false);
		csdd.setWrapText(true);// 自动换行

		String mainInfo = "";
		if (json.getJSONObject("mainInfo") != null) {
			mainInfo = "公司:" + UserContext.get().getCompanyName();
			String materielCode = json.getJSONObject("mainInfo").getString("materielCode");
			if (materielCode != null) {
				mainInfo = mainInfo + "  物料编码:" + materielCode;
			}
			String materielName = json.getJSONObject("mainInfo").getString("materielName");
			if (materielName != null) {
				mainInfo = mainInfo + "  物料名称:" + materielName;
			}
			String projectName = json.getJSONObject("mainInfo").getString("projectName");
			if (projectName != null) {
				mainInfo = mainInfo + "  项目名称:" + projectName;
			}
			String planCode = json.getJSONObject("mainInfo").getString("planCode");
			if (planCode != null) {
				mainInfo = mainInfo + "  计划编码:" + planCode;
			}
			String containerName = json.getJSONObject("mainInfo").getString("containerName");
			if (containerName != null) {
				mainInfo = mainInfo + "  容器名称:" + containerName;
			}
			String addressName = json.getJSONObject("mainInfo").getString("addressName");
			if (addressName != null) {
				mainInfo = mainInfo + "  地点名称:" + addressName;
			}
			String userName = json.getJSONObject("mainInfo").getString("userName");
			if (userName != null) {
				mainInfo = mainInfo + "  操作人:" + userName;
			}
			mainInfo = mainInfo + " --- 货物追溯报表";
		} else {
			mainInfo = "公司:" + UserContext.get().getCompanyName() + " --- 货物追溯报表";
		}
		// 创建第一行，并设置其单元格格式
		HSSFRow rowTitle = sheet.createRow((short) 0);
		rowTitle.setHeight((short) 500);
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 16)); // 合并单元格 1：开始行 2：结束行 3：开始列 4：结束列
		HSSFCell cellTitle = rowTitle.createCell(0);
		cellTitle.setCellValue(mainInfo);
		cellTitle.setCellStyle(csm);

		JSONArray rows = json.getJSONArray("dataInfo");
		for (int i = 0; i < rows.size(); i++) {
			// 表格赋值
			HSSFRow rowData = sheet.createRow((short) i + 1);
			rowData.setHeight((short) 300);
			Object[] cels = rows.getJSONArray(i).toArray();
			if (i == 0) {
				// 第一行开始是列头数据
				for (int x = 0; x < cels.length; x++) {
					HSSFCell cell = rowData.createCell(x);
					// 设置单元格的内容
					cell.setCellValue(cels[x].toString());
					cell.setCellStyle(csdt);
					sheet.setColumnWidth(x, cels[x].toString().getBytes().length * 2 * 256);
				}
			} else {
				// 第二行开始是列表数据
				for (int x = 0; x < cels.length; x++) {
					HSSFCell cell = rowData.createCell(x);
					// 设置单元格的内容
					if (x == cels.length - 1) {
						if (("notphoto").equals(cels[x].toString())) {
							cell.setCellValue("无照片");
						} else {
							cell.setCellValue("查看照片");
							String sheetName = "第" + i + "行数据的照片";
							HSSFSheet photoSheet = workbook.createSheet(sheetName);
							// 画图的顶级管理器，一个sheet只能获取一个（一定要注意这点）
							HSSFPatriarch patriarch = photoSheet.createDrawingPatriarch();
							CellPoint cellPoint = new CellPoint(0, 1);
							List<String> pics = picService.getPics(cels[x].toString());
							for (String string : pics) {
								File fileF = new File("/image.jpg");
								File fileT = new File(
										"//home//images//bartalks//" + string.substring(string.lastIndexOf("/") + 1));
								ChangeImageSizeUtil.resizeImage(fileT, fileF);
								cellPoint = ExcelWriteImgUtil.whiteImg(cell, sheetName, patriarch, workbook, fileF,
										cellPoint);
							}
						}
					} else {
						cell.setCellValue(cels[x].toString());
						cell.setCellStyle(csdd);
					}
					if(cels[x].toString().getBytes().length==0) {
						sheet.autoSizeColumn(x);
					}else {
						int colWidth = sheet.getColumnWidth(i)*2;
						if(colWidth<255*256){
			                sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);    
			            }else{
			                sheet.setColumnWidth(i,6000);
			            }
					}
				}
			}

		}
		return workbook;
	}

	

}
